//
//  RegisterViewController.swift
//  testRxSwift
//
//  Created by 火星人 on 2017/7/26.
//  Copyright © 2017年 火星人. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift

class RegisterViewController: BaseViewController {

    var registerView: RegisterView!
    let disposed = DisposeBag()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.registerView = self.view as! RegisterView
        registerView.registerButton.isEnabled = false
        
        let viewModel = RegisterViewModel(input: (
            registerView.nameTextField.rx.text.orEmpty.asObservable(),
            registerView.pwdTextField.rx.text.orEmpty.asObservable(),
            registerView.repwdTextField.rx.text.orEmpty.asObservable()
        ))
        
        viewModel.nameValidator
            .bind(to: registerView.nameLabel.rx.validateResult)
            .disposed(by: disposed)
        
        viewModel.pwdValidator
            .bind(to: registerView.pwdLabel.rx.validateResult)
            .disposed(by: disposed)
        
        viewModel.repwdValidator
            .bind(to: registerView.repwdLabel.rx.validateResult)
            .disposed(by: disposed)
        
        viewModel.buttonValidator
            .subscribe { [weak self] (eve) in
                let ok = eve.element
                if let ok = ok {
                    self?.registerView.registerButton.isEnabled = ok
                }
                else{
                    self?.registerView.registerButton.isEnabled = false
                }
            }
            .disposed(by: disposed)
        
        
        registerView.nameTextField.rx.controlEvent(.editingDidEnd).subscribe { (eve) in
            self.registerView.pwdTextField.becomeFirstResponder()
        }.disposed(by: disposed)
        
        registerView.pwdTextField.rx.controlEvent(.editingDidEnd).subscribe { (eve) in
            self.registerView.repwdTextField.becomeFirstResponder()
        }.disposed(by: disposed)
        
    }

}

extension Reactive where Base: UILabel{
    var validateResult: UIBindingObserver<Base, ValidateResult> {
        return UIBindingObserver(UIElement: base, binding: { (label, result) in
            label.textColor = result.textColor
            label.text = result.description
        })
    }
}


